/*
 *   Copyright 2023 <a href="mailto:asialjim@hotmail.com">Asial Jim</a>
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.asialjim.encommunicate.base.rsa.util;

import com.asialjim.encommunicate.base.rsa.RSAKeyPairProperty;
import com.asialjim.encommunicate.base.rsa.SimpleRSAEnDecrypt;
import com.asialjim.encommunicate.base.rsa.SimpleRSASigner;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * RSA 工具
 *
 * @author Copyright © <a href="mailto:asialjim@hotmail.com">Asial Jim</a>   Co., LTD
 * @version 1.0
 * @since 2023/2/27, &nbsp;&nbsp; <em>version:1.0</em>, &nbsp;&nbsp; <em>java version:17</em>
 */
public abstract class AbstractRSAUtil {
    protected RSAKeyPairProperty keyPairProperty;
    protected SimpleRSAEnDecrypt enDecrypt;
    protected SimpleRSASigner signer;

    public AbstractRSAUtil(RSAKeyPairProperty keyPairProperty) {
        this.keyPairProperty = keyPairProperty;

        this.enDecrypt = new SimpleRSAEnDecrypt();
        this.signer = new SimpleRSASigner();

        this.enDecrypt.setPairProperty(keyPairProperty);
        this.signer.setPairProperty(keyPairProperty);
    }


    /**
     * 加密
	 * @param source {@link String source}
     * @return {@link String 加密串}
     * @since 2023/2/27
     */
    public String encrypt(String source){
        return enDecrypt.encrypt(source);
    }

    public byte[] encrypt(byte[] source){
        return enDecrypt.encrypt(source);
    }

    // 加签
    public String decrypt(String source){
        return enDecrypt.decrypt(source);
    }

    public InputStream decrypt(InputStream inputStream){
        byte[] decrypt = enDecrypt.decrypt(inputStream);
        return new ByteArrayInputStream(decrypt);
    }

    // 解密
    public String sign(String source){
        return signer.sign(source);
    }

    public String sign(byte[] source){
        return signer.sign(source);
    }

    // 验签
    public void verify(String source, String signature){
        if (!signer.checkSign(source,signature))
            throw new IllegalStateException("请求数据被篡改");
    }

    public void verify(InputStream inputStream, String signature){
        if (!signer.checkSign(inputStream,signature))
            throw new IllegalStateException("请求数据被篡改");
    }
}